package com.zhuodewen.ai.config.international;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Locale;

/**
 * 语言配置拦截器
 */
@Configuration
public class AcceptLanguageInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的国际化/多语言标识: Accept-Language
        String language = request.getHeader("Accept-Language");
        System.out.println("国际化/多语言 Accept-Language: " + language);

        if (language != null && !language.isEmpty()) {
            try{
                String[] splitLanguage = language.split("_");
                if (splitLanguage.length > 1) {
                    // 根据请求头参数, 初始化本地语言和地区
                    Locale locale = new Locale(splitLanguage[0], splitLanguage[1]);
                    LocaleContextHolder.setLocale(locale);
                }
            } catch (Exception e) {
                LocaleContextHolder.setLocale(Locale.CHINA);
            }
        }
        return true;
    }
}
